<template>
  <b-col>
    <b-row>
      <NavigationBar :type="0" />
    </b-row>
    <!-- 这里需要用到富文本编辑器组件 -->
    <b-row>
      <b-container class="bg-white rounded-bottom border">
        <!-- 网站中标题之类的参数 -->
        <b-row class="mt-2">
          <b-col class="col-auto" style="font-size:16px">
            <b-row class="pl-3" style="width:100px">
              文章标题:
            </b-row>
          </b-col>
          <b-col class="pl-0 col-4">
            <b-input placeholder="文章标题" v-model="title" size="sm" />
          </b-col>
        </b-row>
        <b-row class="mt-2">
          <b-col class="col-auto">
            <b-row class="pl-3" style="width:100px">
              话题圈:
            </b-row>
          </b-col>
          <b-col class="pl-0 col-2">
            <!-- 分类数据列表 -->
            <b-form-input v-model="zone" size="sm" list="classList" />
            <datalist id="classList">
              <option style="width:100px" v-for="cate in category" :key="cate">{{cate}}</option>
            </datalist>
          </b-col>
        </b-row>
        <!-- 封面图 -->
        <b-row class="mt-2">
          <b-col class="col-auto pr-0">
            <b-row class="pl-3" style="width:100px">
              封面图:
            </b-row>
          </b-col>
          <b-col class="col-auto">
            <ImgCutter :cutWidth="960" :cutHeight="540" :boxWidth="1280" :boxHeight="720" :sizeChange="true" :toolBoxOverflow="false" :originalGraph="false" :tool="false" rate="16:9"
              @cutDown="cutDown" :quality="0.9">
              <template #open>
                <b-img class="rounded border" width="370" height="200" :src="imgPreview.dataURL" title="点击选择图片" />
              </template>
            </ImgCutter>
          </b-col>
          <b-col class="text-left" align-self="end">
            <b-row style="width:320px">
              <b-col>
                <span style="color:red">温馨提示</span>：文章编辑时标题会显示在正上方，思考正文和标题显示的位置以免文章内容错位难看
              </b-col>
            </b-row>
          </b-col>
        </b-row>
        <!-- 富文本编辑框 -->
        <b-row class="mt-2">
          <b-col>
            <Toolbar class="border rounded-top" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
            <Editor class="border rounded-bottom" style="height: 470px; overflow-y: hidden;" v-model="html" :value="html" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="onCreated" />
          </b-col>
        </b-row>
        <!-- 提交行 -->
        <b-row align-h="end" class="mt-2 mb-2">
          <b-col class="col-auto">
            <b-btn @click="draft" variant="primary">存草稿</b-btn>
          </b-col>
          <b-col class="col-auto pl-0">
            <b-btn @click="issue" variant="success"><span class="iconfont icon-navigation" />发布</b-btn>
          </b-col>
        </b-row>
      </b-container>

      <!-- 存一个模拟框 说不定用得到 -->
      <!-- <b-modal title="点击上传图片" header-class="border-0" footer-class="border-0" button-size="sm" id="img" hide-header-close ok-title="发布" cancel-title="取消"
      :no-close-on-backdrop="true" aria-hidden="true" centered>

    </b-modal> -->
    </b-row>
  </b-col>

</template>
<script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import ImgCutter from 'vue-img-cutter'
import toastr from 'toastr'
import NavigationBar from '../NavigationBar';
export default Vue.extend({
  components: { Editor, Toolbar, ImgCutter, NavigationBar },
  data() {
    return {
      editor: null,
      html: '',
      toolbarConfig: {
        excludeKeys: [
          'todo',
          'group-video',
          'insertLink',
          "codeBlock",
          "fullScreen",
          "uploadImage",
          "undo",
          "redo",
          "|"
        ]
      },
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'defaut', // or 'simple'

      //网站相关的参数 标题之类的……
      title: "",
      category: [
        '杂谈'
      ],  //数据从服务器查出来
      zone: null,
      //剪裁图片的预览
      imgPreview: {
        dataURL: 'https://s1.imagehub.cc/images/2023/02/27/56ebf4e62c4efabb75d43d423e35614f.jpeg',
        file: null,
      },
    }
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    //将剪裁图片返回并预览
    cutDown(res) {
      this.imgPreview = res;
    },
    //点击存草稿和发布
    draft() {
      localStorage.setItem("article", JSON.stringify({
        title: this.title,
        html: this.html,
        zone: this.zone
      }));
      if (Object.prototype.hasOwnProperty.call(localStorage, "article")) {
        toastr.success("存入草稿", "", { timeOut: 3000 });
      }
    },
    issue() {
      if (this.html == null || this.title == null || this.zone == null || this.imgPreview.file == null) {
        toastr.error("标题、圈子、内容、封面图", "请将内容填写完整!", { timeOut: 3000 });
        return
      }
      this.title = this.title.replace(/\s+/g, '');
      if (this.title.length == 0) {
        toastr.error("标题不能只有空格", "格式错误!", { timeOut: 3000 });
        return
      }
      this.zone = this.zone.replace(/\s+/g, '');
      if (this.zone.length == 0) {
        toastr.error("话题区不能只有空格", "格式错误!", { timeOut: 3000 });
        return
      }
      if (this.html.length < 50) {
        toastr.error("内容太少", "格式错误!", { timeOut: 3000 });
        return
      }
      var article = JSON.stringify({
        title: this.title,
        zone: this.zone,
        content: this.html,
      });
      //转换为json请求头
      article = new Blob([article], {
        type: 'application/json',
      })
      //创建表单对象
      let formData = new FormData();
      formData.append("article", article);
      formData.append("file", this.imgPreview.file);
      this.$httpIssue.articleIssue(formData).then((res) => {
        if (res == "1") {
          localStorage.removeItem("article");
          toastr.success("发布成功", "", { timeOut: 2000 });
          setTimeout(() => {
            this.$router.replace({
              path: "/HomePage"
            });
          }, 2000)
        }
      }).catch((err) => {
        console.log(err);
      });
      // console.log("发布文章\n" + article);
    }
  },
  created() {
    if (localStorage.getItem("article") != null) {
      let data = JSON.parse(localStorage.getItem("article"));
      // console.log(data.title);
      this.html = data.html;
      this.title = data.title;
      this.zone = data.zone;
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
})
</script>
<style scoped>
.form-control:focus,
.btn:focus {
  outline: none;
  box-shadow: none;
}
</style>
